package com.lc.file;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;

public class FileChannelTest {
	private RandomAccessFile accessFile;
	private FileChannel fileChannel;

	FileChannelTest() {
		try {
			accessFile = new RandomAccessFile("nio-data.txt", "rw");
			fileChannel = accessFile.getChannel();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	/**
	 * FileChannel读数据
	 */
	public void readFileChannel() {
		try {
			ByteBuffer bBuffer = ByteBuffer.allocate(48);
			int readSize;
			fileChannel.position(0);
			do {
				readSize = fileChannel.read(bBuffer);
				bBuffer.flip();
				System.out.println(Charset.forName("UTF-8").decode(bBuffer));
				bBuffer.clear();
			} while (readSize != -1);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
		}
	}

	/**
	 * FileChannel写数据
	 */
	public void writeFileChannel() {
		try {
			String newData = "\nNew String to write to file..." + System.currentTimeMillis();
			ByteBuffer bBuffer = ByteBuffer.allocate(48);
			fileChannel.position(fileChannel.size()); // 定位末尾，接着输入
			bBuffer.put(newData.getBytes("UTF-8"));
			bBuffer.clear();
			while (bBuffer.hasRemaining()) {
				fileChannel.write(bBuffer);
			}
			bBuffer.flip();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
		}
	}

	public static void main(String[] args) {
		FileChannelTest writeCannel = new FileChannelTest();
		writeCannel.writeFileChannel();
		//FileChannelTest readCannel = new FileChannelTest();
		writeCannel.readFileChannel();
	}
}
